package com.bishe.demo.modules.common.service.impl;


import com.bishe.demo.modules.common.entity.ImageType;
import com.bishe.demo.modules.common.entity.ResourceConfigBean;
import com.bishe.demo.modules.common.entity.ResultEntity;
import com.bishe.demo.modules.common.service.UploadService;
import com.bishe.demo.modules.other.service.impl.ImageServiceImpl;
import com.bishe.demo.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


@Service
public class UploadServiceImpl implements UploadService {

    private final static Logger LOGGER = LoggerFactory.getLogger(ImageServiceImpl.class);
    @Autowired
    private ResourceConfigBean resourceConfigBean;

    @Override
    public ResultEntity<String> uploadImage(MultipartFile file, String imageType) {
        if (file.isEmpty()) {//若传过来的文件为空
            return new ResultEntity<>(ResultEntity.ResultStatus.FAILED.code, "文件为空");
        }
        String destFolderStringBig = String.format("%s%s", resourceConfigBean.getLocalPathForWindow(), imageType);//获取文件应该存放的位置
        File destFolderBig = new File(destFolderStringBig);//创建文件夹用于存放上传的文件的文件夹
        if (!destFolderBig.exists()) {//如果文件不存在
            destFolderBig.mkdir();//创建该文件夹
        }

        String imageName = String.format("%s.%s", System.currentTimeMillis(), FileUtil.getFileType(file.getOriginalFilename()));//获取文件的文件名和后缀名（为了保证文件的唯一性使用时间进行标识）
        String absolutePath = String.format("%s/%s", destFolderStringBig, imageName);//获取文件的绝对路径
        String relativePath = String.format("%s%s/%s", resourceConfigBean.getResourcePath(), imageType, imageName);//获取文件的相对路径
        try {
            File destFile = new File(absolutePath);//创建文件存放上传的文件
            file.transferTo(destFile);//写入文件
            ImageType type = ImageType.getImageTypeByName(imageType) == null ? ImageType.PROFILE_SMALL : ImageType.getImageTypeByName(imageType);//获取文件的文件类型
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.debug(e.getMessage());
            return new ResultEntity<>(ResultEntity.ResultStatus.FAILED.code, "上传失败");
        }

        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.code, "上传成功", relativePath);
    }
}
